<!--
 * @Author: Neko
 * @Date: 2021-05-13 13:41:17
 * @LastEditTime: 2021-05-18 16:13:11
 * @LastEditors: Neko
-->
<!DOCTYPE html>
<html lang="zh_CN">
  <head>
    <title>Checkout Pay</title>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=none"
    />
    <title>Checkout Frames v2</title>
    <style>
      *,
      *::after,
      *::before {
        box-sizing: border-box;
      }
      html {
        padding: 1rem;
        background-color: #fff;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
          Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
      }
      #payment-form {
        width: 315px;
        margin: 0 auto;
      }
      iframe {
        width: 100%;
      }
      .one-liner {
        display: flex;
        flex-direction: column;
      }
      #pay-button {
        border: none;
        border-radius: 3px;
        color: #fff;
        font-weight: 500;
        height: 40px;
        width: 100%;
        background-color: #13395e;
        box-shadow: 0 1px 3px 0 rgba(19, 57, 94, 0.4);
      }
      #pay-button:active {
        background-color: #0b2a49;
        box-shadow: 0 1px 3px 0 rgba(19, 57, 94, 0.4);
      }
      #pay-button:hover {
        background-color: #15406b;
        box-shadow: 0 2px 5px 0 rgba(19, 57, 94, 0.4);
      }
      #pay-button:disabled {
        background-color: #697887;
        box-shadow: none;
      }
      #pay-button:not(:disabled) {
        cursor: pointer;
      }
      .card-frame {
        border: solid 1px #13395e;
        border-radius: 3px;
        width: 100%;
        margin-bottom: 8px;
        height: 40px;
        box-shadow: 0 1px 3px 0 rgba(19, 57, 94, 0.2);
      }
      .card-frame.frame--rendered {
        opacity: 1;
      }
      .card-frame.frame--rendered.frame--focus {
        border: solid 1px #13395e;
        box-shadow: 0 2px 5px 0 rgba(19, 57, 94, 0.15);
      }
      .card-frame.frame--rendered.frame--invalid {
        border: solid 1px #d96830;
        box-shadow: 0 2px 5px 0 rgba(217, 104, 48, 0.15);
      }
      .success-payment-message {
        color: #13395e;
        line-height: 1.4;
      }
      .token {
        color: #b35e14;
        font-size: 17rpx;
        font-family: monospace;
      }
      @media screen and (min-width: 310px) {
        .one-liner {
          /* flex-direction:row */
        }
        .card-frame {
          /* width:318px; */
          margin-bottom: 0;
        }
        #pay-button {
          margin-top: 10px;
          /* width:175px; */
          /* margin-left:8px */
        }
      }
    </style>
    <script
      type="text/javascript"
      src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"
    ></script>
  </head>

  <body>
    <script src="https://cdn.checkout.com/js/framesv2.min.js"></script>

    <form
      id="payment-form"
      method="POST"
      action="https://merchant.com/charge-card"
    >
      <div class="one-liner">
        <div class="card-frame">
          <!-- form will be added here -->
        </div>
        <!-- add submit button -->
        <button id="pay-button" disabled>
          PAY
        </button>
      </div>

      <p class="success-payment-message"></p>
    </form>
    <script>
      const query = window.location.href.split('?')[1]

      const queryObj = query.split('&').reduce((prev, current) => {
        const [key, value] = current.split('=')
        prev[key] = value
        return prev
      }, {})

      var BASE_URL = decodeURIComponent(queryObj.url)

      // if (queryObj.platform === 'app') {
      //   var BASE_URL = 'http://api-mall.test.tomorni.com'
      // } else {
      //   var BASE_URL = '/api'
      // }

      var serializer = obj => {
        if (!obj) return ''

        return Object.entries(obj)
          .reduce((prev, [key, value]) => {
            prev.push(key + '=' + value)
            return prev
          }, [])
          .join('&')
      }

      function simpleAjax({
        url,
        method,
        data,
        token,
        successFn,
        failFn = function() {}
      }) {
        const xhr = new XMLHttpRequest()
        if (method.toUpperCase() === 'GET') {
          data = serializer(data)
          url = BASE_URL + url + '?' + data
        } else {
          url = BASE_URL + url
        }

        xhr.open(method.toUpperCase(), url, true)

        xhr.setRequestHeader('Authorization', token)

        xhr.onreadystatechange = function() {
          console.log(xhr.readyState, url)
          if (xhr.readyState === XMLHttpRequest.DONE) {
            const status = xhr.status

            if (status === 0 || (status >= 200 && status < 400)) {
              const response = JSON.parse(xhr.response)
              if (response.code === 200) {
                successFn(response)
              } else {
                failFn(response)
              }
            }
          }
        }

        if (method.toUpperCase() === 'POST') {
          xhr.send(JSON.stringify(data))
        } else {
          xhr.send(null)
        }
      }
      
      document.addEventListener('UniAppJSBridgeReady', () => {
        const changeAjax = function() {
          simpleAjax({
            url: '/checkout/getPayInfo',
            method: 'GET',
            data: {
              orderId: queryObj.order_id
            },
            token: queryObj.token,
            successFn: function(res) {
              var payButton = document.getElementById('pay-button')
              var form = document.getElementById('payment-form')

              Frames.init(res.data.publicKey)

              Frames.addEventHandler(
                Frames.Events.CARD_VALIDATION_CHANGED,
                function(event) {
                  payButton.disabled = !Frames.isCardValid()
                }
              )

              Frames.addEventHandler(Frames.Events.CARD_TOKENIZED, function(
                event
              ) {
                simpleAjax({
                  url: '/checkout/tokenPay',
                  method: 'POST',
                  token: queryObj.token,
                  data: {
                    orderId: queryObj.order_id,
                    token: event.token
                  },
                  successFn: function(res) {
                    if (res.data) {
                      uni.redirectTo({
                        url:
                          '/pages/order/check/check?orderid=' +
                          queryObj.order_id
                      })
                    } else {
                      const el = document.querySelector(
                        '.success-payment-message'
                      )
                      el.innerHTML = res.message

                      payButton.disabled = false
                    }
                  },

                  failFn: function(e) {
                    if (e.code === -1) {
                      const el = document.querySelector(
                        '.success-payment-message'
                      )
                      el.innerHTML = e.message

                      changeAjax()

                      payButton.disabled = false
                    }
                    // uni.redirectTo({
                    //   url: '/pages/order/check/check?orderid=' + queryObj.order_id
                    // })
                  }
                })

                // var el = document.querySelector(".success-payment-message");
                // el.innerHTML = "Card tokenization completed<br>" +
                //   "Your card token is: <span class=\"token\">" + event.token + "</span>";
              })

              form.addEventListener('submit', function(event) {
                payButton.disabled = true // disables pay button once submitted
                event.preventDefault()
                Frames.submitCard()
              })
            }
          })
        }

        changeAjax()
      })
    </script>
  </body>
</html>
